<template>
  <!-- 页面内容 -->
  <view class="container">
    <view class="background-container">
      <image class="header-bg" src="@/static/headerBgi.png" mode="widthFix">
      </image>
    </view>
    <view class="status-bar" v-if="!isApp"></view>
    <view class="navbar">青年实干家计划</view>
    <view class="header-content">
      <view class="searchContainer">
        <input v-model="searchText" class="customSearch" placeholder="请搜索您感兴趣的岗位" @confirm="search" confirm-type="search"/>
        <image class="searchIcon" src="@/static/search.png"></image>
      </view>
      <view class="card">
        <view class="information" v-if="showInfo" @click="goDetail(information)">
          <image src="@/static/notice.png"></image>
          <view class="signAnswer">
            <view v-if="information.answer ===0" :style="{color:'#474b53',fontSize:'28rpx'}">
              您已报名岗位
              <view class="signupIng" :style="{color:'#3b7de8'}">
                【<span class="signupText">{{information.name}}</span>】
              </view>
            </view>
            <view v-else-if="information.answer ===1" :style="{color:'#474b53',fontSize:'28rpx'}">
              恭喜您，您已报名的
              <view class="signupIng" :style="{color:'#3b7de8'}">
                【<span class="signupText">{{information.name}}</span>】
              </view>
              岗位，匹配成功！点击岗位名称可查看详情。
            </view>
            <view v-else-if="information.answer ===2" :style="{color:'#474b53',fontSize:'28rpx'}">
              非常抱歉，经审核您不符合
              <view class="signupIng" :style="{color:'#FF0000'}">
                【<span class="signupText">{{information.name}}</span>】
              </view>
              岗位要求，匹配失败。点击岗位名称可查看详情。
            </view>
          </view>
        </view>
        <view class="position">
          <view v-for="(item, index) in position" :key="index">
            <view class="select" :class="{'active':activeIndex===index}" @click="hadelWork(item,index)">
              {{item.deptName}}
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 已报名弹窗 -->
    <view class="mask" v-if="showModal">
      <view class="modelContainer">
        <view :style="{color:'#474b53',fontSize:'36rpx',textAlign:'center',fontWeight:'bold'}">温馨提醒</view>
        <image src="@/static/close.png" @click="showModal = false"></image>
        <view class="modelContent" :style="{color:'#474b53',fontSize:'28rpx'}">
          您已报名岗位
          <view class="modelName" :style="{color:'#3b7de8'}">
            <span class="modelTitle">{{information.name}}</span>
          </view>
          无法再次报名
        </view>
        <button @click="goDetail(information)">去查看</button>
      </view>
    </view>
    <view class="content">
      <view class="work" v-if="showWork">
        <view class="workInfo">
          <view v-for="(item ,index) in work.list" :key="index" @click="detail(item)">
            <view class="name">{{item.name}}</view>
            <view class="contact">
              <view class="info">
                <view class="workContact">
                  <image src="@/static/contact.png"></image>
                  <view class="charge">{{item.charge}}</view>
                  <view class="divider"></view>
                  <view class="phone">{{item.phone}}</view>
                </view>
                <view class="sit">
                  <image src="@/static/company.png"></image>
                  <view style="flex: 1; word-break: break-all;">{{item.sit}}</view>
                </view>
              </view>
              <view class="count">
                <view class="number">
                  {{item.count}}
                </view>
                岗位数量
              </view>
            </view>
            <view class="workDetail">
              <view class="titleContainer">
                <view class="workTitle">课题名称</view>
                <view class="title">{{item.title}}</view>
              </view>
              <view class="goalContainer">
                <view class="workGoal">课题目标</view>
                <view class="goal">
                  <rich-text :nodes="item.goal" class="rich-text-content"></rich-text>
                </view>
              </view>
            </view>
            <view class="sign">
              我要报名
            </view>
            <view class="divi"></view>
          </view>
        </view>
      </view>
      <view class="empty" v-if="!showWork">
        <image src="../../static/empty.png"></image>
        暂无岗位
      </view>
    </view>
  </view>
</template>

<script setup>
  import {
    ref,
    onMounted,
    getCurrentInstance,
    watch,
    inject
  } from 'vue';
  import {
    onPullDownRefresh,
    onShow,
    onReachBottom
  } from "@dcloudio/uni-app"
  import {
    handleWechatCallback,
    checkLoginStatus,
    getQueryString
  } from '../../utils/login.js'


  import {
    getCityList
  } from '@/api/work/position.js';
  import {
    getWorkBysearch
  } from '@/api/work/search.js';
  import {
    getInformation
  } from '@/api/work/information.js';
  onPullDownRefresh(() => {
    console.log("下拉刷新")
    work.value.pageNum = 1
    hadelWork(position.value[activeIndex.value], activeIndex.value)
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 100)

  })
  // 通过 inject 获取全局属性（更安全的方式）
  const globalProperties = inject('globalProperties')
  // 获取当前实例（仅在同步代码中有效）
  const instance = getCurrentInstance()
  onShow(() => {
    showApproveInfo()
  })
  onReachBottom(() => {
    loadMore()
  })
  onMounted(() => {
    // 获取URL参数（修复核心问题：定义code和state变量）
    const code = getQueryString('code');
    const state = getQueryString('state');

    if (code && state) {
      // 处理微信登录回调
      handleWechatCallback(code, state).then(success => {
        if (success) {
          isLogin.value = true;
          userInfo.value = uni.getStorageSync('userInfo');
          showWelcomeModal.value = true;
          getTotal();
        }
      });
    } else {
      // 检查登录状态
      checkLoginStatus().then(loggedIn => {
        isLogin.value = loggedIn;
        if (loggedIn) {
          userInfo.value = uni.getStorageSync('userInfo');
        } else {
          // 未登录，触发全局登录流程
          // 方法1：使用 inject 获取全局属性（推荐）
          console.log(globalProperties);
          if (globalProperties && globalProperties.$login) {
            globalProperties.$login.init();
          }
          // // 方法2：使用保存的实例（仅在同步代码中有效）
          // else if (instance && instance.appContext) {
          //   instance.appContext.config.globalProperties.$login.init();
          // }
          // // 方法3：直接引入登录模块（最安全）
          // else {
          //   import('@/main.js').then(({
          //     createApp
          //   }) => {
          //     const {
          //       app
          //     } = createApp()
          //     app.config.globalProperties.$login.init()
          //   })
          // }
        }
      });
    }
    getTotal()
  })
  const getTotal = () => {
    getCityList().then((res) => {
      if (res.code === 200) {
        position.value = res.data
        hadelWork(position.value[0], 0)
      }
    })
  }
  
  const showApproveInfo = () => {
    getInformation().then((res) => {
      if (res.code === 200) {
        information.value = res.data ? {
          signupId: res.data.signUpId,
          name: res.data.post,
          answer: res.data.status
        } : {
          answer: -1,
          name: '',
          signupId: ''
        }
      }
    })
  }

  const isLogin = ref(false)
  const userInfo = ref(null)

  const showLoginModal = () => {
    uni.showModal({
      title: '登录提示',
      content: '正在进行微信授权登录...',
      showCancel: false,
      confirmText: '确定'
    })
  }

  const showWelcomeModal = () => {
    uni.showModal({
      title: '欢迎回来',
      content: `欢迎回来，${userInfo.value?.nickname || '用户'}`,
      showCancel: false,
      confirmText: '确定'
    })
  }

  const position = ref([])
  const activeIndex = ref(0)
  const work = ref({
    list: [],
    pageNum: 1,
    pageSize: 10,
    total: 0,
    pages: 0
  })
  
  // const work = ref([{
  //     id:0,
  //     name: "养老服务优化专员兼职团组织副书记",
  //     charge: "冯冬梅",
  //     phone: "17812802740",
  //     sit: "隆化县泉济温泉旅游开发有限公司",
  //     title: "隆化县泉济温泉旅游开发有限公司",
  //     goal: "通过与高校合作，为企业带来新的技术思路和方法，开发出更具有市场竞争力的等离子技术装备，满足半导体制造、航空航天、新能源...",
  //     count: 1
  //   }
  // ])
  const detail = (item) => {
    console.log('点击的整个item对象:', item)
    console.log('requireId:', item.requireId)
    console.log('即将跳转到的URL:', "/pages/detail/detail?id=" + encodeURIComponent(item.requireId))

    if (!item || !item.requireId) {
      console.error('错误：item 或 requireId 为空', item)
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      })
      return
    }

    uni.navigateTo({
      url: "/pages/detail/detail?id=" + encodeURIComponent(item.requireId),
      success: () => {
        console.log('跳转成功')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
      }
    })
  }
  const information = ref({
    answer: -1, // 初始化默认值
    name: '',
    signupId: ''
  })
  const showModal = ref(false)
  const showInfo = ref(false)
  watch(() => information.value.answer, (newVal) => {
    if (newVal === -1 || newVal === 2) {
      showModal.value = false

    } else {
      showModal.value = true

    }
    if (newVal === -1) {
      showInfo.value = false
    } else {
      showInfo.value = true
    }
  })
 
  //跳转到界面
  const goDetail = () => {
    showModal.value = false,
      uni.navigateTo({
        url: '/pages/signup/detail?id=' + encodeURIComponent(information.value.signupId)
      })
  }
  const getSearch = (params)=>{
    getWorkBysearch(params).then(res => {
      if (res.code === 200) {
        work.value = {
          total: res.total,
          pages: res.pages,
          pageNum: work.value.pageNum,
          pageSize: work.value.pageSize,
          list: (params.pageNum === 1)
          ? res.rows.map(job => ({
              name: job.post,
              goal: job.content,
              sit: job.unit,
              title: job.project,
              charge: job.contact,
              phone: job.number,
              count: (job.quantity - job.recruited),
              requireId: job.requireId
            }))
          : [...work.value.list, ...res.rows.map(job => ({
              name: job.post,
              goal: job.content,
              sit: job.unit,
              title: job.project,
              charge: job.contact,
              phone: job.number,
              count: (job.quantity - job.recruited),
              requireId: job.requireId
            }))]
        }
        showWork.value = work.value.total>0
      }
    })
  }
  const handlePageChange = (pageNum) => {
    if (pageNum < 1 || pageNum > work.value.pages) return
    work.value.pageNum = pageNum
    hadelWork(position.value[activeIndex.value], activeIndex.value)
  }
  const loadMore = () => {
    if (work.value.pageNum >= work.value.pages) return
    work.value.pageNum += 1
    getSearch({pageNum: work.value.pageNum,
      pageSize: work.value.pageSize,
      searchQuery: searchText.value.trim(),
      deptId: position.value[activeIndex.value].deptId})
  }
  const searchText = ref('')
  const showWork = ref('')
  const hadelWork = (item, index) => {
    activeIndex.value = index
    showWork.value = false
     work.value.pageNum =1
    getSearch({pageNum:  work.value.pageNum ,
      pageSize: work.value.pageSize,
      searchQuery: searchText.value.trim(),
      deptId: position.value[activeIndex.value].deptId,})
  
  }
  
  const search = () => {
     work.value.pageNum =1
    getSearch({pageNum:  work.value.pageNum ,
      pageSize: work.value.pageSize,
      searchQuery: searchText.value.trim(),
      deptId: position.value[activeIndex.value].deptId,})
  }
</script>

<style>
  .container {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
  }

  .background-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: -1;
  }

  .header-bg {
    width: 100%;
    height: auto;
  }

  .navbar {
    padding: 30rpx 0;
    color: #ffffff;
    font-size: 36rpx;
    text-align: center;
  }

  .searchContainer {
    position: relative;
    width: 690rpx;
    margin: 30rpx;
  }

  .customSearch {
    width: 100%;
    height: 72rpx;
    border-radius: 36rpx;
    background-color: #fff;
    padding-left: 70rpx;
    padding-right: 30rpx;
    font-size: 26rpx;
    color: rgba(183, 187, 190, 0.8);
    font-family: Source Han Sans CN;
    box-sizing: border-box;
  }

  .searchIcon {
    position: absolute;
    left: 30rpx;
    top: 50%;
    transform: translateY(-50%);
    width: 25rpx;
    height: 26rpx;
  }

  .card {
    background-color: #ffffff;
    border-radius: 32rpx 32rpx 0 0;
    padding-top: 20rpx;
  }

  .information {
    display: flex;
    width: 690rpx;
    background-color: #f8f9fd;
    border-radius: 10rpx;
    margin: 0 30rpx;
    min-height: 76rpx;
    box-sizing: border-box;
    padding: 24rpx;
    font-size: 26rpx;
    align-items: flex-start;
  }

  .signupIng {
    display: inline;
  }

  .signupText {
    border-bottom: 2rpx solid currentColor;
  }

  .mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;
  }

  .modelContainer {
    width: 520rpx;
    padding: 36rpx;
    background-color: #ffffff;
    border-radius: 10rpx;
    box-sizing: border-box;
    position: relative;
  }

  .modelContainer image {
    width: 20rpx;
    height: 20rpx;
    position: absolute;
    top: 28rpx;
    right: 28rpx;

  }

  .modelContent {
    width: 100%;
    text-align: center;
    align-items: center;
    justify-content: center;
    margin: 48rpx 0;
  }

  .modelName {
    display: initial;

  }

  .modelTitle {
    border-bottom: 2rpx solid currentColor;
    display: initial;
  }

  .modelContainer button {
    background-color: #3b7de8;
    color: #ffffff;
    width: 216rpx;
    height: 60rpx;
    border-radius: 10rpx;
    text-align: center;
    font-size: 24rpx;

  }

  .information image {
    width: 23rpx;
    height: 28rpx;
    display: inline-block;
    margin-right: 12rpx;
    vertical-align: middle;
    min-width: 23rpx;
  }

  .position {
    display: flex;
    gap: 24rpx;
    padding: 40rpx 30rpx 30rpx 30rpx;
    overflow-x: auto;
    white-space: nowrap;
    -webkit-overflow-scrolling: touch;
    border-bottom: 1rpx solid rgba(183, 187, 190, 0.7);
    ;
  }

  .select {
    font-size: 26rpx;
    color: #b7bbbe;
    font-family: Source Han Sans CN;
    display: inline-block;
    padding-right: 24rpx;
  }

  .select.active {
    font-size: 30rpx;
    color: #3b7de8;
  }

  .content {
    flex: 1;
  }

  .empty {
    color: #d1d4d5;
    font-size: 30rpx;
    display: flex;
    flex-direction: column;
    height: 100%;
    justify-content: center;
    align-items: center;
    text-align: center;
    margin-top: 160rpx;
  }

  .empty image {
    width: 150rpx;
    height: 130rpx;
    margin-bottom: 24rpx;
  }

  .work {
    flex: 1;
  }

  .workInfo {
    padding: 48rpx 30rpx;

  }

  .name {
    font-size: 34rpx;
    color: #474b53;
    margin-bottom: 30rpx;
    font-weight: bold;
  }

  .workInfo image {
    width: 36rpx;
    height: 36rpx;
    display: inline-block;
    margin-right: 17rpx;
    flex-shrink: 0;
  }

  .contact {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .info {
    flex: 1;
  }

  .count {
    color: #3b7de8;
    font-size: 20rpx;
    width: 104rpx;
    height: 84rpx;
    border-radius: 10rpx;
    text-align: center;
    background-color: #f8f9fd;
  }

  .number {
    font-size: 34rpx;
    font-weight: bold;
  }

  .workContact {
    font-size: 26rpx;
    align-items: center;
    color: #7f8387;
    display: flex;
    margin-bottom: 12rpx;
  }

  .divider {
    width: 1rpx;
    height: 20rpx;
    background-color: #b7bbbe;
    margin: 0 17rpx;
  }

  .sit {
    font-size: 26rpx;
    color: #7f8387;
    display: flex;
    align-items: center;
    min-width: 36rpx;
  }

  .workDetail {
    padding: 24rpx 30rpx;
    background-color: #f8f9fd;
    margin: 20rpx 0;
  }

  .workTitle {
    font-size: 26rpx;
    color: #3b7de8;
    width: 104rpx;
    white-space: nowrap;
  }

  .workGoal {
    font-size: 26rpx;
    color: #3b7de8;
    width: 104rpx;
    white-space: nowrap;
  }

  .titleContainer {
    display: flex;
  }

  .goalContainer {
    display: flex;
  }

  .title {
    margin-left: 20rpx;
    font-size: 26rpx;
    color: #474b53;
    width: 518rpx;

  }

  .goal {
    margin-left: 20rpx;
    font-size: 26rpx;
    color: #474b53;
    width: 518rpx;
  }

  .goal rich-text {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 3;
    white-space: pre-wrap;
    word-break: break-word;
  }

  .sign {
    width: 690rpx;
    background-color: #e2f1ff;
    color: #3b7de8;
    border-radius: 10rpx;
    height: 72rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26rpx;
  }

  .divi {
    height: 6rpx;
    background-color: #f4f6f7;
    margin: 42rpx 0;
  }

  .pages {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 40rpx 0;
    font-size: 28rpx;
  }

  .pageBtn {
    padding: 10rpx 30rpx;
    margin: 0 20rpx;
    border: 1rpx solid #3b7de8;
    border-radius: 8rpx;
    color: #3b7de8;

    &disabled {
      color: #ccc;
      border-color: #ccc;
      pointer-events: none;
    }
  }

  .pageInfo {
    color: #666;
  }

  .rich-text-content {
    width: 100%;
    overflow-x: hidden;
    word-break: break-all;
  }
</style>